<template>
  <div class="edit-container">
    <el-form ref="ruleFormRef" :model="form" label-width="auto" size="large" class="form-container" :rules="rules">
      <el-form-item label="客户姓名" prop="customerName" required>
        <el-input v-model="form.customerName" disabled />
      </el-form-item>
      <el-form-item label="客户喜好" prop="preferences">
        <el-input v-model="form.preferences" />
      </el-form-item>
      <el-form-item label="注意事项">
        <el-input v-model="form.attention" />
      </el-form-item>
      <el-form-item label="其他备注">
        <el-input v-model="form.remark" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">保存</el-button>
        <el-button @click="cancleEdit">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup name='edit'>
import { ref, watch } from "vue";
import { saveOrUpdateInfo } from "@/api/customer/customerpreference/index.js";
import { ElNotification } from 'element-plus'

// 表单信息
const form = ref({
  customerName: '',
  preferences: '',
  attention: '',
  remark: ''
})

// 校验必选项规则
const rules = {
  preferences: [{ required: true, message: '请输入客户喜好', trigger: 'blur' }]
}

// 接收父组件传递的props
const props = defineProps({
  closeEdit: Function,
  currentRow: Object
})

// 监听editId变化
watch(() => props.currentRow, (newVal) => {
  if (newVal) {
    form.value = { ...newVal }
  }
}, { immediate: true })

// 创建引用 用于表单必选项验证
const ruleFormRef = ref()

// 保存按钮点击事件
const onSubmit = () => {
  // Element Plus 表单组件的一个方法调用，用于触发表单验证
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      saveOrUpdateInfo(form.value).then(success => {
        ElNotification({
          title: '消息',
          type: 'success',
          message: "保存成功",
        })
        props.closeEdit(true);
      })
    } else {
      ElNotification({
        title: '错误',
        type: 'error',
        message: error.message || "请输入必选项"
      })
      return false;
    }
  })
}

// 点击取消按钮
const cancleEdit = () => {
  props.closeEdit(false);
}

</script>

<style scoped>
.edit-container {
  /* 水平居中对齐 */
  justify-content: center;
  /* 垂直居中对齐 */
  align-items: center;
  /* 高度占满父容器 */
  height: 100%;
}

.form-container {
  width: 400px;
  /* 如果允许换行，那么换行后，多行元素中的每一行也会垂直居中 */
  justify-content: center;
  /* 垂直居中对齐 */
  align-items: center;
}
</style>